import {
  PAGE_KEYS,
  CONDITION_KEYS,
  hasOwn,
  isPlainObject,
  clone,
} from '@shared';

import {
  isIncludeLabel,
  isExcludeLabel,
  isEndLabel,
  formatPlatformValue,
  joinSubpackagePagePath,
} from '../utils';

/**
 * 过滤页面相关的跨平台信息
 * @param {Object | Array} pages 主包/分包页面数据
 * @returns 处理后的结果
 */
export function filterPlatformsOfPages(pages) {
  // 结果
  const result = [];
  // 分包根目录
  const subpackageRoot =
    isPlainObject(pages) && hasOwn(pages, PAGE_KEYS.SUBPACKAGE_ROOT)
      ? pages[PAGE_KEYS.SUBPACKAGE_ROOT]
      : '';
  // 列表数据
  const recordList = subpackageRoot ? pages.pages : pages;
  // 条件编译的值
  let includeValue, excludeValue, currentRecord;
  // 遍历
  for (let index = 0, size = recordList.length; index < size; index++) {
    currentRecord = recordList[index];
    if (isIncludeLabel(currentRecord)) {
      includeValue = formatPlatformValue(currentRecord[CONDITION_KEYS.INCLUDE]);
      continue;
    } else if (isExcludeLabel(currentRecord)) {
      excludeValue = formatPlatformValue(currentRecord[CONDITION_KEYS.EXCLUDE]);
      continue;
    } else if (isEndLabel(currentRecord)) {
      includeValue = excludeValue = null;
      continue;
    }
    // clone 一个新的页面对象
    const currentPage = clone(currentRecord);
    if (includeValue) {
      currentPage[CONDITION_KEYS.INCLUDE] = [].concat(includeValue);
    } else if (excludeValue) {
      currentPage[CONDITION_KEYS.EXCLUDE] = [].concat(excludeValue);
    }
    // 分包
    if (subpackageRoot) {
      // 标记分包根目录
      currentPage[PAGE_KEYS.SUBPACKAGE_PAGE] = subpackageRoot;
      // 完善页面路径
      currentPage.path = joinSubpackagePagePath(
        currentPage.path,
        subpackageRoot
      );
    }
    result.push(currentPage);
  }

  return result;
}
